import Taro from '@tarojs/taro'
import Utils from './utils'

const __DEBUG = true


var __DATA = new Map()

var initialized = false

const Global = {
  isDebug: (__DEBUG == true),

  config:{
    apiServerDebug:'http://localhost:10085/api/v1',       //生产环境应删除mock文件夹
    apiServer: 'https://ms2.hybaodigital.com/api/v1',
    cdnServer:'https://cdn.hybaodigital.com/ms2',       //在cdn卷下建立ms2文件夹再上传资源
  },

  init:()=>{
    // 检查local里是否有缓存
    try {
      const res = Taro.getStorageInfoSync()
      Utils.debug('res.keys=',res.keys)
      res.keys.map(key=>{
        let value = Taro.getStorageSync(key)
        __DATA.set(key,value)
      })
      initialized = true
    } catch (e) {
      // Do something when catch error
    }
  },

  set : (key,val,type=0) => {
    let value = {
      type:type,       // 0:memory, 1:localStorage
      data:val
    }
    __DATA.set(key,value)
    if(type ==1){
      // 存本地
      Taro.setStorageSync(key,value)
    }
    Utils.debug('global.set(\''+key+'\')=',val)
  },

  get : key => {
    if(!initialized){
      Global.init()
    }
    let value = __DATA.get(key)
    if(value){
      return value.data
    }
    else{
      return value
    }
  },

  has: key => {
    if(!initialized){
      Global.init()
    }
    return __DATA.has(key)
  },

  remove: key => {
    __DATA.delete(key)
    // 移除本地缓存
    Taro.removeStorage({ key: key})
  }
}


export default Global
